package com.pet.common.config;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Swagger3 配置文件 <br>
 * 访问UI界面地址：http://localhost:8080/swagger-ui/index.html <br>
 *
 * @author Centaurea
 */
@EnableOpenApi
@Configuration
public class Swagger3Config implements WebMvcConfigurer {
  @Bean
  public Docket createRestApi() {
    // 返回文档摘要信息
    return new Docket(DocumentationType.OAS_30)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
        .paths(PathSelectors.any())
        .build();
  }

  /** 生成接口信息，包括标题、联系人等 */
  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("爱宠邦后台管理系统接口文档")
        .description("包含基础的接口信息")
        .contact(new Contact("Centaurea", "https://www.charon4strix.com", "charon4strix@qq.com"))
        .version("1.0")
        .build();
  }

  /** 通用拦截器排除swagger设置，所有拦截器都会自动加swagger相关的资源排除信息 */
  @SuppressWarnings("unchecked")
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    try {
      Field registrationsField =
          FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
      List<InterceptorRegistration> registrations =
          (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
      if (registrations != null) {
        for (InterceptorRegistration interceptorRegistration : registrations) {
          interceptorRegistration
              .excludePathPatterns("/swagger**/**")
              .excludePathPatterns("/webjars/**")
              .excludePathPatterns("/v3/**")
              .excludePathPatterns("/doc.html");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
